package com.qfmy.service.impl.novel;

import com.qfmy.mapper.novel.HistoryMapper;
import com.qfmy.service.novel.HistoryService;
import com.qfmy.vo.novel.HistoryVo;
import common.exception.BaseException;
import common.login.LoginUser;
import common.login.LoginUserHolder;
import common.result.ResultCodeEnum;
import model.entity.novel.History;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 清风明月
 * @Package com.qfmy.service.impl.novel
 * @date 2025/6/7
 * @description 浏览历史
 */
@Service
@SuppressWarnings("all")
public class HistoryServiceImpl implements HistoryService {

    /**
     * 注入mapper
     */
    @Autowired
    private HistoryMapper historyMapper;


    /**
     * 获取最新浏览记录
     * @return
     */
    @Override
    public HistoryVo getNewestHistory() {
        //获取用户id
        Long userId = getUserId();
        //获取最新的浏览记录
        History history = historyMapper.selectNewestHistoryByUserId(userId);
        HistoryVo historyVo = new HistoryVo();
        //进行对象拷贝
        if (history != null) {
            historyVo.setHistoryId(history.getHistoryId());
            historyVo.setPage(history.getPage());
            historyVo.setNovel(history.getNovel());
            historyVo.setChapter(history.getChapter());
            return historyVo;
        }
        return null;
    }

    /**
     * 分页获取浏览历史
     * @param pageNum
     * @param size
     * @return
     */
    @Override
    public List<HistoryVo> getHistoryByPage(Integer pageNum, Integer size) {
        //获取用户id
        Long userId = getUserId();
        //计算分页
        Integer start = getStart(pageNum, size);
        //分页获取数据
        List<History> histories = historyMapper.getHistoryByPage(userId, start, size);
        //拷贝数据
        List<HistoryVo> historyVos = Copy(histories);
        return historyVos;
    }

    /**
     * 清空历史记录
     */
    @Override
    public void clearHistory() {
        Long userId = getUserId();
        historyMapper.clearHistory(userId);
    }

    /**
     * 删除历史记录
     * @param historyId
     */
    @Override
    public void clearHistoryById(Long historyId) {
        //获取用户id
        Long userId = getUserId();
        historyMapper.clearHistoryById(historyId,userId);
    }

    /**
     * 保存历史记录
     * @param novelId
     * @param chapterId
     * @param page
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveHistory(Long novelId, Long chapterIndex, Integer page) {
        //获取用户id
        Long userId = getUserId();
        //根据用户id和说id查询历史记录
        History history = historyMapper.selectHistory(userId, novelId);
        //判断是否存在
        if(history == null)
        {
            //创建历史记录
            history = new History();
            history.setUserId(userId.intValue());
            history.setNovelId(novelId.intValue());
            history.setChapterIndex(chapterIndex.intValue());
            history.setPage(page);
            historyMapper.insert(history);
        }else
        {
            //更新历史记录
            history.setChapterIndex(chapterIndex.intValue());
            history.setPage(page);
            historyMapper.update(history);
        }
    }

    /**
     * 获取用户阅读历史
     * @param novelId
     * @return
     */
    @Override
    public HistoryVo getHistoryByNovelId(Long novelId) {
        //获取用户id
        Long userId = getUserId();
        History history = historyMapper.selectHistory(userId, novelId);
        if(history != null)
        {
            HistoryVo historyVo = new HistoryVo();
            historyVo.setHistoryId(history.getHistoryId());
            historyVo.setPage(history.getPage());
            historyVo.setChapter(history.getChapter());
            historyVo.setLastReadTime(history.getLastReadTime());
            return historyVo;
        }
        return null;
    }

    /**
     * 拷贝数据
     * @param histories
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private List<HistoryVo> Copy(List<History> histories) {
        //判断集合是否为空
        if ( histories  == null || histories.size() == 0 || histories.isEmpty())
        {
            return new ArrayList<>();
        }
        //循环遍历数据
        List<HistoryVo> historyVos = new ArrayList<>();
        for (History history : histories) {
            HistoryVo historyVo = new HistoryVo();
            BeanUtils.copyProperties(history,historyVo);
            historyVos.add(historyVo);
        }
        return historyVos;
    }

    /**
     * 计算分页
     * @param pageNum
     * @param size
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private Integer getStart(Integer pageNum, Integer size) {
        if (pageNum == null || size == null)
        {
            size = 20;
            pageNum = 1;
        }
        return (pageNum - 1) * size;
    }

    /**
     * 获取用户id
     * @return
     */
    public Long getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断是否存在
        if(loginUser == null)
        {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return loginUser.getUserId();
    }
}
